﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

namespace Gamev1
{
    public class Animation
    {
        private enum Direction
        {
            Left = 0,
            Right = 1
        }
        public Texture2D[] AnimationTextures;
        private int frames = 0;
        private int totalFrames;
        private float delay;
        private float elapsedTime;
        private int direction;

        public Animation(float delayPerFrame)
        {
            delay = delayPerFrame;
        }

        public void initializeTextures(ContentManager content, string[] animationPath)
        {
            int length = animationPath.Length;
            AnimationTextures = new Texture2D[length];
            loadContent(content, animationPath);
        }

        public void Update(GameTime gameTime, int direction)
        {
            checkDirection(direction);
            DoAnimation(gameTime);
        }

        public void Draw(SpriteBatch spriteBatch, Sprite sprite)
        {
            if (direction == (int)Direction.Left)
            {
                spriteBatch.Draw(AnimationTextures[frames], sprite.Position, null, sprite.Color, 0f, Vector2.Zero, 1f, SpriteEffects.FlipHorizontally, 0f);
            }
            else if (direction == (int)Direction.Right)
            {
                spriteBatch.Draw(AnimationTextures[frames], sprite.Position, sprite.Color);
            }
        }

        private void checkDirection(int direction)
        {
            this.direction = direction;
        }

        private void DoAnimation(GameTime gameTime)
        {
            elapsedTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            totalFrames = AnimationTextures.Length;
            if (elapsedTime >= delay)
            {
                if (frames >= totalFrames - 1)
                {
                    frames = 0;
                }
                else
                {
                    frames++;
                }
                elapsedTime = 0f;
            }
        }

        private void loadContent(ContentManager content, string[] animationPath)
        {
            for (int index = 0; index < animationPath.Length; index++)
            {
                AnimationTextures[index] = content.Load<Texture2D>(animationPath[index]);
            }
        }

        public int Frames
        {
            get { return frames; }
            set { frames = value; }
        }
    }
}
